package com.kaili.common.exception;
import com.kaili.common.response.CommonStatus;
import com.kaili.common.response.RestStatus;
import com.kaili.common.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpStatus;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kaili.common.response.ResponseData;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

/**
 * 自定义异常拦截器
 * @Copyright: Copyright (c) 2017
 * @Company: 杭州凯立通信有限公司
 * @author zhengs
 * @version 1.0.0 2017年7月20日 下午3:36:01
 */
@ControllerAdvice
public class RestExceptionHandler {

	@Autowired
	private MessageSource messageSource;

	@ResponseBody
	@ExceptionHandler(RestException.class)
	public ResponseData handle(RestException e) {
		RestStatus restStatus = e.getStatus();
		String msg = CommonUtil.getMessage(messageSource,restStatus.reasonPhrase());
		return new ResponseData(restStatus.value(),msg);
	}

	@ResponseBody
	@ExceptionHandler(BaseExcept.class)
	public ResponseData handle(BaseExcept e) {
		IResponseStatus responseStatus = e.getResponseStatus();
		String msg = CommonUtil.getMessage(messageSource,responseStatus.getMsg());
		return new ResponseData(responseStatus.getCode(),msg);
	}

	@ResponseBody
	@ExceptionHandler(value = {BindException.class, MethodArgumentNotValidException.class})
	public ResponseData valiteHandler(Exception exception) {
		BindingResult bindResult = null;
		if (exception instanceof BindException) {
			bindResult = ((BindException) exception).getBindingResult();
		} else if (exception instanceof MethodArgumentNotValidException) {
			bindResult = ((MethodArgumentNotValidException) exception).getBindingResult();
		}
		String msg;
		if (bindResult != null && bindResult.hasErrors()) {
			msg = bindResult.getAllErrors().get(0).getDefaultMessage();
			if (msg.contains("NumberFormatException")) {
				msg = "参数类型错误！";
			}
		}else {
			msg = "系统繁忙，请稍后重试...";
		}

		return new ResponseData(HttpStatus.BAD_REQUEST.value(), msg);
	}

	@ResponseBody
	@ExceptionHandler(value = ConstraintViolationException.class)
	public ResponseData handle(ConstraintViolationException e) {
		StringBuilder sb = new StringBuilder();
		for(ConstraintViolation violation : e.getConstraintViolations()){
			sb.append(violation.getMessage());
		}

		return new ResponseData(HttpStatus.BAD_REQUEST.value(), sb.toString());
	}
}